package com.leonzhangxf.spel.reference;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.spel.SpelParserConfiguration;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.SimpleEvaluationContext;

import java.lang.reflect.Method;

/**
 * Functions
 * <p>
 * You can extend SpEL by registering user-defined functions that
 * can be called within the expression string.
 * The function is registered through the EvaluationContext.
 *
 * @author leonzhangxf
 * @date 20190427
 */
public class Functions {

    public static void main(String[] args) throws NoSuchMethodException {
        Method method = StringUtils.class.getDeclaredMethod("reverseString", String.class);

        EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build();
        context.setVariable("reverseStr", method);

        SpelParserConfiguration parserConfiguration =
            new SpelParserConfiguration(true, true);
        SpelExpressionParser parser = new SpelExpressionParser(parserConfiguration);

        System.out.println(parser.parseExpression("#reverseStr('abc')").getValue(context, String.class));
    }

    public static class StringUtils {

        public static String reverseString(String input) {
            StringBuilder backwards = new StringBuilder(input.length());
            for (int i = 0; i < input.length(); i++) {
                backwards.append(input.charAt(input.length() - 1 - i));
            }
            return backwards.toString();
        }
    }
}
